
--// phieuchuyentienkhacnh : insert
--// giaodich : insert
--// taikhoan : update

create proc sp_ChuyenTienKhacNH @MaTKChuyen char(13), @MaTKNhan char(13), @NHangNhan int,
		 @SoTien money, @MaNVGD char(10), @ChiNhanhGD int
as begin tran
	-- kiem tra MaTK ton tai
	if exists(select * from Tai_Khoan where MaTK = @MaTKChuyen) begin
		-- insert vao Giao_Dich
		declare @MaGD int
		set @MaGD = ((select count(*) from Giao_Dich) + 1)
		declare @phi money
		set @phi = 100
		insert into Giao_Dich values (@maGD, GetDate(),'GD-007', @MaNVGD, @MaTKChuyen, @phi, @ChiNhanhGD)
		-- kiem tra thao tac insert co thanh cong hay ko?
		if(@@error <> 0) begin
			rollback tran
			return 0
		end
		-- insert vao bang PHIEU_CHUYEN_TIEN_DEN_TK_KHAC_NH
		declare @MaPhieu int
		set @MaPhieu = ((select count(*) from PHIEU_CHUYEN_TIEN_DEN_TK_KHAC_NH) + 1)
		insert into PHIEU_CHUYEN_TIEN_DEN_TK_KHAC_NH values (@maPhieu, @MaGD, @MaTKNhan,@NHangNhan,@SoTien )
		-- kiem tra thao tac insert co thanh cong hay ko?
		if(@@error <> 0) begin
			rollback tran
			return 0
		end

		-- cap nhat cho tai khoan ....
		update Tai_Khoan set SoDuNo = SoDuNo + @SoTien, SoDu = SoDu - @SoTien where MaTK = @MaTKChuyen
		if(@@error <> 0) begin
			rollback tran
			return 0
		end
	end
	else begin
		rollback tran
		return 0
	end

commit